//
//  BonusTransferViewController.m
//  HQJFacilitator
//
//  Created by mymac on 16/9/22.
//  Copyright © 2016年 Fujian first time iot technology investment co., LTD. All rights reserved.
//

#import "BonusTransferViewController.h"
#import "pickerView.h"
#import "NoticeView.h"

@interface BonusTransferViewController ()<UITextFieldDelegate>
{
    BOOL isHaveDian;
    BOOL isBonusNil;
    BOOL isUserName;
    CGFloat distance ;
}
@property (nonatomic,strong)UILabel *headerBonusLabel;
@property (nonatomic,strong)UILabel *payerLabel;
@property (nonatomic,strong)UILabel *bonusNumberLabel;
@property (nonatomic,strong)UILabel *TransactionPasswordLabel;
@property (nonatomic,strong)UITextField *bsNumberTextFileld;
@property (nonatomic,strong)UITextField *tPswTextFileld;
@property (nonatomic,strong)UIButton *submitButton;
@property (nonatomic,strong)UILabel *canCashLabel;
@property (nonatomic,copy)  NSString *bounsStr;
@property (nonatomic,strong)UITextField *typeTextField;
@property (nonatomic,strong)UILabel *typeDownLabel;
@property (nonatomic,strong)pickerView *pickView;
@property (nonatomic,copy) NSString *oribonusStr;
@property (nonatomic,copy) NSString *cusbonusStr;
@property (nonatomic,strong)NoticeView *popView;
@property (nonatomic,strong) NSMutableArray * typeArray;
@end

@implementation BonusTransferViewController

-(UILabel *)headerBonusLabel {
    if (!_headerBonusLabel) {
        _headerBonusLabel = [[UILabel alloc]init];
        _headerBonusLabel.backgroundColor = [ManagerEngine getColor:@"fff2b2"];
        _headerBonusLabel.frame = CGRectMake(0, 64, WIDTH, 44);
        //        _headerBonusLabel.textColor = [UIColor ];
        _headerBonusLabel.textAlignment = NSTextAlignmentCenter;
        _headerBonusLabel.font = [UIFont systemFontOfSize:15 weight:.2f];
//        [self.view addSubview:_headerBonusLabel];
    }
    
    
    return _headerBonusLabel;
}


-(UITextField *)typeTextField {
    if (!_typeTextField) {
        _typeTextField = [[UITextField alloc]init];
        _typeTextField.backgroundColor = [UIColor whiteColor];
        _typeTextField.text = @"服务商转自身会员";
        _typeTextField.borderStyle = UITextBorderStyleRoundedRect;
        _typeTextField.delegate = self;
        [self.view addSubview:_typeTextField];
    }
    
    
    return _typeTextField;
}

-(UILabel *)typeDownLabel {
    if (!_typeDownLabel) {
        
        _typeDownLabel = [[UILabel alloc]init];
        _typeDownLabel.text = @"积分转到自身会员,需扣除5%手续费";
        _typeDownLabel.textColor = [ManagerEngine getColor:@"f54949"];
        _typeDownLabel.font = [UIFont systemFontOfSize:13];
        [self.view addSubview:_typeDownLabel];
    }
    
    return _typeDownLabel;
}


-(UILabel *)payerLabel {
    
    if (!_payerLabel) {
        _payerLabel = [[UILabel alloc]init];
        _payerLabel.font = [UIFont systemFontOfSize:17];
        [self.view addSubview:_payerLabel];
    }
    
    return _payerLabel;
}
-(UILabel *)bonusNumberLabel {
    if (!_bonusNumberLabel) {
        _bonusNumberLabel = [[UILabel alloc]init];
        _bonusNumberLabel.font = [UIFont systemFontOfSize:17];
        _bonusNumberLabel.text = @"积分数:";
        [self.view addSubview:_bonusNumberLabel];
        
    }
    
    
    return _bonusNumberLabel;
}
-(UITextField *)bsNumberTextFileld {
    if (!_bsNumberTextFileld) {
        _bsNumberTextFileld = [[UITextField alloc]init];
        _bsNumberTextFileld.textColor = [UIColor blackColor];
        _bsNumberTextFileld.backgroundColor = [UIColor whiteColor];
        _bsNumberTextFileld.layer.masksToBounds = YES;
        _bsNumberTextFileld.layer.cornerRadius = 5;
        _bsNumberTextFileld.placeholder = @" 请输入转移积分数额";
        _bsNumberTextFileld.clearButtonMode = UITextFieldViewModeAlways;
        _bsNumberTextFileld.keyboardType = UIKeyboardTypeDecimalPad;
        _bsNumberTextFileld.delegate = self;
        [self.view addSubview:_bsNumberTextFileld];
    }
    
    return _bsNumberTextFileld;
    
}




-(UILabel *)TransactionPasswordLabel {
    if (!_TransactionPasswordLabel) {
        _TransactionPasswordLabel = [[UILabel alloc]init];
        _TransactionPasswordLabel.font = [UIFont systemFontOfSize:17];
        _TransactionPasswordLabel.text = @"交易密码:";
        [self.view addSubview:_TransactionPasswordLabel];
    }
    
    
    
    return _TransactionPasswordLabel;
}

-(UITextField *)tPswTextFileld {
    if (!_tPswTextFileld) {
        _tPswTextFileld = [[UITextField alloc]init];
        _tPswTextFileld.layer.masksToBounds = YES;
        _tPswTextFileld.layer.cornerRadius = 5;
        _tPswTextFileld.placeholder = @" 请输入6位交易密码";
        _tPswTextFileld.textColor = [UIColor blackColor];
        _tPswTextFileld.backgroundColor = [UIColor whiteColor];
        _tPswTextFileld.clearButtonMode = UITextFieldViewModeAlways;
        _tPswTextFileld.keyboardType = UIKeyboardTypeNumberPad;
        _tPswTextFileld.secureTextEntry = YES;
        [self.view addSubview:_tPswTextFileld];
    }
    
    
    
    return _tPswTextFileld;
}
-(UILabel *)canCashLabel {
    
    if (!_canCashLabel) {
        _canCashLabel = [[UILabel alloc]init];
        _canCashLabel.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:_canCashLabel];
        
    }
    
    return _canCashLabel;
}


-(UIButton *)submitButton {
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
        _submitButton.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
        _submitButton.layer.masksToBounds = YES;
        _submitButton.layer.cornerRadius = 5;
        [self.view addSubview:_submitButton];
    }
    
    
    
    return _submitButton;
}

//-()

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [ManagerEngine getColor:@"f5f5f5"];
    self.typeArray = [NSMutableArray array];
    isUserName = NO;
    distance = 30;
    
    if ([FileEngine filePathNameReadName:@"is_shopaholic" andstye:filePathlocationStyle]) {
        if (![[FileEngine filePathNameReadName:@"is_shopaholic" andstye:filePathlocationStyle] isEqualToString:@"0"]) {
            
            [self.typeArray addObject:@"服务商转自身会员"];
            [self.typeArray addObject:@"自身会员转服务商"];
     
        } else {
            [self.typeArray addObject:@"服务商转自身会员"];
            
        }

        
        //        [self is_shopaholic:[FileEngine filePathNameReadName:@"is_shopaholic" andstye:filePathlocationStyle]];
    } else {
//        [self.typeArray addObject:@"服务商转自身会员"];
        
    }
    HQJLog(@"类型数组：%@，====，%@",[FileEngine filePathNameReadName:@"is_shopaholic" andstye:filePathlocationStyle],self.typeArray);
    
    
    [self content];
    [self signalJudgment];
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self upPopView:[NSDictionary dictionary]];
    [self requstBonus];
}
//-(void)viewDidDisappear:(BOOL)animated {
//    [super viewDidDisappear:animated];
//    [self upPopView:nil];
//    [_popView dismssPopView];
//    
//}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self upPopView:nil];

    [_popView dismssPopView];

    
}
#pragma mark --
#pragma mark --- 更新广告条
-(void)upPopView:(NSDictionary *)dic{
    if (_popView) {
        [_popView removeFromSuperview];
    }
    _popView = [[NoticeView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, 44) andtitle:dic andType:2];
    [self.view addSubview:_popView];

    
}
#pragma mark --
#pragma mark --- 积分数量
-(void)bounsNumerLabel {
    
    
    self.headerBonusLabel.text = [NSString stringWithFormat:@"当前服务商账号有%@个积分",[Manager sharedManager].bonus];
    
    [ManagerEngine setTextColor:self.headerBonusLabel FontNumber:[UIFont systemFontOfSize:15 weight:.2f]  AndRange:[Manager sharedManager].bonus AndColor:[ManagerEngine getColor:@"f54949"]];
}



#pragma mark --
#pragma mark ---视图内容
-(void)content {
    [self bounsNumerLabel];
    
    
    /******支付方******/
    self.payerLabel.text = [NSString stringWithFormat:@"交易类型:"];
    CGFloat payerRect = [ManagerEngine setTextWidthStr:self.payerLabel.text andFont:[UIFont systemFontOfSize:17]];
    self.payerLabel.sd_layout.
    leftSpaceToView(self.view,15).
    topSpaceToView(self.headerBonusLabel,20).
    heightIs(20).
    widthIs(payerRect);
    self.typeTextField.sd_layout.leftSpaceToView(self.payerLabel,5).topSpaceToView(self.headerBonusLabel,15).heightIs(40).widthIs(WIDTH-15*2-5-payerRect);
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        @WeakObj(self);
    [rightButton bk_addEventHandler:^(id  _Nonnull sender) {
        [selfWeak setTypeTextFieldClick];
    } forControlEvents:UIControlEventTouchUpInside];
    rightButton.frame =CGRectMake(0, 0, 20, 20);
    [rightButton setImage:[UIImage imageNamed:@"DownArrow"] forState:UIControlStateNormal];
    
    
    self.typeTextField.rightView = rightButton;
    self.typeTextField.rightViewMode = UITextFieldViewModeAlways;
    self.typeDownLabel.sd_layout.leftEqualToView(self.typeTextField).topSpaceToView(self.typeTextField,5).heightIs(15).widthIs(WIDTH-15*2-5-payerRect);

    
    UIButton *maskButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [maskButton bk_addEventHandler:^(id  _Nonnull sender) {
                [selfWeak setTypeTextFieldClick];
    } forControlEvents:UIControlEventTouchUpInside];
    maskButton.frame = _typeTextField.bounds;
    [_typeTextField addSubview:maskButton];
    

    
    
    
    /******积分数******/
    self.bonusNumberLabel.sd_layout.
    leftEqualToView(self.payerLabel).
    topSpaceToView(self.payerLabel,50).
    heightIs(20).
    widthIs(60);
    
    /******积分数输入框******/
    self.bsNumberTextFileld.sd_layout.
    leftSpaceToView(self.bonusNumberLabel,0).
    topSpaceToView(self.typeDownLabel,5).
    heightIs(40).
    widthIs(WIDTH-30-60);

    /****交易密码******/
    self.TransactionPasswordLabel.sd_layout.leftEqualToView (self.payerLabel).topSpaceToView(self.bonusNumberLabel,50).heightIs(20).widthIs(80);
    
    /****交易密码输入框*****/
    self.tPswTextFileld.sd_layout.leftSpaceToView(self.TransactionPasswordLabel,0).topSpaceToView(self.bonusNumberLabel,40).heightIs(40).widthIs(WIDTH-30-80);
    
    
    /******提交******/
    self.submitButton.sd_layout.leftEqualToView(self.payerLabel).topSpaceToView(self.tPswTextFileld,20).heightIs(40).widthIs(WIDTH-30);
    
}

#pragma mark --
#pragma mark ---信号处理
-(void)signalJudgment {
    
    RACSignal *validPswSignal = [self.tPswTextFileld.rac_textSignal map:^id(id value) {
        return @([self isValidPsw:value]);
    }];
    RACSignal *validBounsSignal = [self.bsNumberTextFileld.rac_textSignal map:^id(NSString *value) {
        
        if ([value isEqualToString:@""]) {
            self.canCashLabel.text = [NSString stringWithFormat:@"对方可得积分:0.00"];
        } else {
//            @"服务商转自身会员",@"自身会员转服务商"
            if ([_typeTextField.text isEqualToString:@"服务商转自身会员"]) {
                  self.canCashLabel.text = [NSString stringWithFormat:@"对方可得积分:%.2f",[value floatValue]-[value floatValue]*0.05];
            } else {
                  self.canCashLabel.text = [NSString stringWithFormat:@"对方可得积分:%.2f",[value floatValue]];
            }
          
        }
        [self upLayout];
        return @([self textFieldChanged:value]);
    }];

    
    RACSignal *signUp = [RACSignal combineLatest:@[validPswSignal,validBounsSignal] reduce:^id(NSNumber *pswValid,NSNumber *bounsValid){
        return @([pswValid boolValue]&&[bounsValid boolValue]);
    }];
    [signUp subscribeNext:^(NSNumber * signUpActive) {
        self.submitButton.enabled = [signUpActive boolValue];
        if ([signUpActive boolValue]) {
            self.submitButton.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
            
        } else {
            self.submitButton.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
            
        }
        
    }];
    [[self.submitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        if ([_typeTextField.text isEqualToString:@"服务商转自身会员"]) {
            HQJLog(@"你有多少积分啊:%f\n%f",[self.bsNumberTextFileld.text floatValue], [_oribonusStr floatValue]);
            if ([self.bsNumberTextFileld.text floatValue] > [_oribonusStr floatValue]) {
                [ManagerEngine homeSvpStr:@"亲，您的积分好像没有那么多哦" andcenterView:self.view andStyle:promptViewDefault];
            } else {
                [self requstTransfe];
                
            }

            
        }else {
            if ([_bsNumberTextFileld.text doubleValue]>[_cusbonusStr doubleValue]) {
                [ManagerEngine homeSvpStr:@"亲，您会员的积分好像没有那么多哦" andcenterView:self.view andStyle:promptViewDefault];
            } else {
                [self requstTransfe];
                
            }

            
        }
        
    }];
    
}

#pragma mark --
#pragma mark ---密码的输入框条件
-(BOOL)isValidPsw:(NSString *)text {
    if (text.length==6) {
        return YES;
    } else if (text.length >6) {
        
        [ManagerEngine homeSvpStr:@"交易密码不能超过6位数" andcenterView:self.view andStyle:promptViewDefault];
        return NO;
    } else {
        return NO;
        
    }
    
    
}

#pragma mark --
#pragma mark ---积分数的输入框条件
-(BOOL)textFieldChanged:(NSString *)text
{
    if ([text floatValue]<=0) {
        return  NO;
    }  else{
        return  YES;
    }
    
}

#pragma mark --
#pragma mark ---手机号的输入框条件
-(BOOL)numerValid:(NSString *)text {
    
    if (text.length==11) {
        return YES;
    }
    return NO;
    
}


#pragma mark --
#pragma mark ---更新布局
-(void)upLayout {
    
    /***可兑换的金额***/
    
    if ([self.canCashLabel.text isEqualToString:@"对方可得积分:0.00"]) {
        self.canCashLabel.textColor = [ManagerEngine getColor:@"999999"];

    } else {
        self.canCashLabel.textColor = [ManagerEngine getColor:@"f54949"];

    }
    
    CGFloat cancashRect = [ManagerEngine setTextWidthStr:self.canCashLabel.text andFont:[UIFont systemFontOfSize:12]];
    self.canCashLabel.sd_layout.leftSpaceToView(self.view,WIDTH- cancashRect-15).topSpaceToView(self.bsNumberTextFileld,5).heightIs(20).widthIs(cancashRect);
    
    
    
    
    
}



#pragma mark --
#pragma mark ---UITextFiled Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //    NSLog(@"输入的内容为%@",textField.text);
    
    if ([self.bsNumberTextFileld.text rangeOfString:@"."].location==NSNotFound) {
        isHaveDian=NO;
    }
    if ([string length]>0)
        
    {
        if ([self.bsNumberTextFileld.text length]>8)
        {
            [ManagerEngine homeSvpStr:@"亲，输入超出限制了哟" andcenterView:self.view andStyle:promptViewDefault];
            
            return NO;
        }
        
        
        unichar single=[string characterAtIndex:0];//当前输入的字符
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            
            
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    [ManagerEngine homeSvpStr:@"亲，您已经输入过小数点了" andcenterView:self.view andStyle:promptViewDefault];
                    
                    [self.bsNumberTextFileld.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                
            }
            else
            {
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[self.bsNumberTextFileld.text rangeOfString:@"."];
                    
                    NSInteger tt = range.location-ran.location;
                    
                    if (tt <= 2){
                        return YES;
                    }else{
                        [ManagerEngine homeSvpStr:@"亲，您最多输入两位小数" andcenterView:self.view andStyle:promptViewDefault];
                        return NO;
                    }
                }
                else
                {
                    return YES;
                    
                }
                
                
            }
        }else{//输入的数据格式不正确
            [ManagerEngine homeSvpStr:@"亲，您输入的格式不正确" andcenterView:self.view andStyle:promptViewDefault];
            [self.bsNumberTextFileld.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
            
        }
        
    }
    
    else
    {
        return YES;
        
    }
    
}
//-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
//    if(textField == self.typeTextField) {
//        return YES;
//        
//    } else  {
//        
//        
//        return YES;
//    }
//
//
//}

#pragma mark --
#pragma mark --- 积分请求
-(void)requstBonus {
    
//    oribonusStr
//    cusbonusStr
    
    [RequestEngine HQJFacilitatorRequestDetailsUrl:[NSString stringWithFormat:@"%@bonusTransfer/memberid/%@",AppOrg_URL,MmberidStr] complete:^(NSDictionary *dic) {
        NSDictionary *oneDic = dic[@"result"];
//NSLog(@"===请求的字典是:%@",dic[@"result"]);
        [self upPopView:oneDic];
        
        _oribonusStr = dic[@"result"][@"oribonus"];
        _cusbonusStr = dic[@"result"][@"cusbonus"];
    } andError:^(NSError *error) {
        
    } ShowHUD:NO];
}



#pragma mark --
#pragma mark ---提交请求

-(void)requstTransfe {
    NSString *urlStr;
    
    if ([self.typeTextField.text isEqualToString:@"服务商转自身会员"]) {
        
        //  -----服务商转自身会员需要扣除5%的手续费
        urlStr = [NSString stringWithFormat:@"%@bonusTransferAction/amount/%@/tradepwd/%@/memberid/%@",AppOrg_URL,self.bsNumberTextFileld.text,self.tPswTextFileld.text,MmberidStr];
        
    }
    if ([self.typeTextField.text isEqualToString:@"自身会员转服务商"]) {
        urlStr = [NSString stringWithFormat:@"%@bonusTransferToSelfOAction/amount/%@/tradepwd/%@/memberid/%@",AppOrg_URL,self.bsNumberTextFileld.text,self.tPswTextFileld.text,MmberidStr];
    }
    
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        if ([dic[@"error"] integerValue] == 0) {
            [self requstBonus];
            [ManagerEngine customAlert:@"转移成功" andViewController:self isBack:YES];
            
        }else {
            
            [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:CustomWindow andStyle:promptViewFadeAway];
            
        }
    } andError:^(NSError *error) {
        
    } ShowHUD:YES];
    
    
}


- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    if (textField == self.typeTextField) {
//        [self setTypeTextFieldClick];
        [self.typeTextField resignFirstResponder];
        
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark --
#pragma mark --- 第一个输入框点击方法
-(void)setTypeTextFieldClick {
    @WeakObj(self);
    _pickView = [[pickerView alloc]initWithFrame:CGRectMake(self.typeTextField.frame.origin.x, self.typeTextField.frame.origin.y+self.typeTextField.frame.size.height, self.typeTextField.frame.size.width, 30 * self.typeArray.count) andTitleAry: self.typeArray];
    [_pickView showView];
    [_pickView setSenderBlock:^(id sender) {
        
        
        selfWeak.typeTextField.text = [NSString stringWithFormat:@"%@",selfWeak.typeArray[[sender integerValue]]];
        if ([sender integerValue] == 0){
            selfWeak.typeDownLabel.hidden = NO;
        } else {
            selfWeak.typeDownLabel.hidden = YES;
            
        }
        selfWeak.bsNumberTextFileld.text = @"";
        selfWeak.tPswTextFileld.text  =@"";
        selfWeak.canCashLabel.text = [NSString stringWithFormat:@"对方可得积分:0.00"];
        [selfWeak upLayout];
    }];
    
    
}
-(void)setup {
    
//    [sup];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
